<template>
	<view class="">
		<view class="searchPage">
			<uni-search-bar focus class="uni-mt-10" radius="18" placeholder="搜索" clearButton="auto" cancelButton="none" @input="search" />
		</view>
		<view class="goods" v-for="(item,i) in searchData" :key="i" @click="goDetail(item)">
			<view class="goods_item">
				{{item.goods_name}}
			</view>
			<uni-icons type="right" />
		</view>
		<view class="historyList" v-show="keyWord === ''">
			<view class="histTop">
				搜索历史<uni-icons type="trash" size="20" @click="clearHis" />
			</view>
			<view class="histhist">
				<view class="histItem" v-for="(val,i) in historyList" :key="i" @click="goList(val)">{{val}}</view>
			</view>
		</view>
	</view>
	
</template>

<script>

	export default {
		data() {
			return {
				timer: null,
				keyWord: '',
				searchData: [],
				// 搜索关键词的历史记录
				historyList: []
			}
		},
		onLoad() {
			this.historyList = JSON.parse(uni.getStorageSync('historyList') || '[]')
		},
		methods:{
			async getSearchData() {
				if (this.keyWord === '') {
					this.searchData = []
					return
				}
				const {data} = await uni.$http.get(`/api/public/v1/goods/qsearch?query=${this.keyWord}`)
				if (data.meta.status !== 200) return uni.$showMsg()
				this.searchData = data.message
				this.historyList.unshift(this.keyWord)
				this.historyList = [...new Set(this.historyList)]
				uni.setStorageSync('historyList',JSON.stringify(this.historyList))
			},
			search(e) {
				if (this.timer) {
					clearTimeout(this.timer)
				}
				this.timer = setTimeout(() => {
					this.keyWord = e.trim()
					this.getSearchData()
				},500)
				
			},
			goDetail(val) {
				uni.navigateTo({
					url:"../goodsDetail/goodsDetail?goods_id=" + val.goods_id
				})
			},
			clearHis() {
				this.historyList = []
				uni.setStorageSync('historyList','[]')
				uni.$showMsg()
			},
			goList(val) {
				uni.navigateTo({
					url:"../goods_list/goods_list?query=" + val
				})
			}
		}
	}
</script>

<style lang="scss">
.searchPage {
	background-color: #c00000;
	position: sticky;
	top: 0;
	z-index: 999;
	.showInput {
		background-color: #fff;
		height: 36px;
		line-height: 36px;
		.uni-icons {
			vertical-align: middle;
		}
		}
}
.goods {
	margin: 0 8rpx;
	height: 80rpx;
	line-height: 80rpx;
	border-bottom: 1px solid #ccc;
	font-size: 24rpx;
	.goods_item {
		width: calc(100% - 34rpx);
		display: inline-block;
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
		vertical-align: bottom; 
	}
}
.historyList {
	.histTop {
		margin: 0 10rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 40px;
		font-size: 13px;
		border-bottom: 1px solid #efefef;
	}
	.histhist {
		display: flex;
		flex-wrap: wrap;
		padding: 0 5px;
		.histItem {
			margin: 5px 5px 0 0;
			height: 32px;
			line-height: 32px;
			padding: 0 12px;
			font-size: 13px;
			border-radius: 3px;
			background-color: #eee;
		}
	}
}
</style>
